<template>
  <view class="container">
    <!-- 1. 顶部搜索栏 -->
    <view class="top-search-bar">
      <!-- <view class="sign-in">
        <image src="" class="signin-icon" mode="aspectFit"></image>
        <text>签到</text>
      </view> -->
      <view class="search-input-wrapper">
        <uni-icons
          type="search"
          size="18"
          color="#999"
          class="search-icon-inner"
        ></uni-icons>
        <input type="text" placeholder="" class="search-input" v-model="keyword" />
      </view>
      <!-- <uni-icons type="camera" size="26" color="#333" class="camera-icon"></uni-icons> -->
      <view class="search-btn" @click="handleSearch">
        <uni-icons type="search" size="22" color="#fff"></uni-icons>
      </view>
    </view>

    <!-- 2. 横向滚动Tab导航 -->
    <scroll-view class="scroll-tabs" scroll-x="true" :show-scrollbar="false">
      <view
        v-for="(tab, index) in tabs"
        :key="index"
        :class="['tab-item', { active: activeTab === index }]"
        @click="changeTab(index)"
      >
        {{ tab.name }}
        <view v-if="tab.tag" class="tab-tag">{{ tab.tag }}</view>
      </view>
    </scroll-view>

    <!-- 3. 快捷入口图标区域 -->
    <!-- <view class="quick-entry">
      <view v-for="(item, index) in quickEntries" :key="index" class="entry-item">
        <image :src="item.icon" mode="aspectFit" class="entry-icon"></image>
        <text class="entry-text">{{ item.name }}</text>
        <view v-if="item.tag" :class="['entry-tag', item.tagType]">{{ item.tag }}</view>
      </view>
    </view> -->

    <!-- 4. "Outlets捡漏" 横向滚动商品区域 -->
    <!-- <view class="outlets-section">
      <view class="outlets-header">
        <image src="/static/images/outlets-icon.png" class="outlets-title-icon" mode="aspectFit"></image>
        <text class="outlets-title-text">闲鱼奥莱</text>
        <text class="outlets-subtitle">电商退换货</text>
      </view>
      <scroll-view class="outlets-scroll" scroll-x="true" :show-scrollbar="false">
        <view v-for="(item, index) in outletItems" :key="index" class="outlet-item">
          <image :src="item.image" mode="aspectFill" class="outlet-image"></image>
          <text v-if="item.price" class="outlet-price">¥{{ item.price }}</text>
          <text v-if="item.desc" class="outlet-desc">{{ item.desc }}</text>
        </view>
      </scroll-view>
    </view> -->

    <!-- 5. 商品列表 (伪瀑布流) -->
    <view class="product-list-title" v-if="activeTab === 1">为你推荐</view>
    <!-- 仅在推荐tab下显示 -->
    <view class="product-list">
      <view class="column">
        <view
          v-for="item in column1Products"
          :key="item.id"
          class="product-item"
          @click="clickProduct(item)"
        >
          <image
            :src="getFirstImageUrl(item.imageUrls)"
            mode="widthFix"
            class="product-image"
          ></image>
          <view class="product-info">
            <view class="product-title">
              <text v-if="item.isFreeShipping" class="shipping-tag">包邮</text>
              {{ item.title }} {{ item.description }}
            </view>
            <view class="product-meta">
              <text class="product-price">¥{{ item.price }}</text>
              <!-- <text class="product-wants">{{ item.viewCount }}人想要</text> -->
            </view>
            <view class="seller-info">
              <image
                :src="item.seller?.sellerAvatar"
                mode="aspectFill"
                class="seller-avatar"
              ></image>
              <text class="seller-name">{{ item.seller?.sellerName }}</text>
              <text
                :class="[
                  'seller-credit',
                  getCreditClass(item.seller?.sellerCredit),
                ]"
                >{{ item.seller?.sellerCredit }}</text
              >
            </view>
          </view>
        </view>
      </view>
      <view class="column">
        <view
          v-for="item in column2Products"
          :key="item.id"
          class="product-item"
          @click="clickProduct(item)"
        >
          <image
            :src="getFirstImageUrl(item.imageUrls)"
            mode="widthFix"
            class="product-image"
          ></image>
          <view class="product-info">
            <view class="product-title">
              <text v-if="item.isFreeShipping" class="shipping-tag">包邮</text>
              {{ item.title }} {{ item.description }}
            </view>
            <view class="product-meta">
              <text class="product-price">¥{{ item.price }}</text>
              <!-- <text class="product-wants">{{ item.viewCount }}人想要</text> -->
            </view>
            <view class="seller-info">
              <image
                :src="item.seller?.sellerAvatar"
                mode="aspectFill"
                class="seller-avatar"
              ></image>
              <text class="seller-name">{{ item.seller?.sellerName }}</text>
              <text
                :class="[
                  'seller-credit',
                  getCreditClass(item.seller?.sellerCredit),
                ]"
                >{{ item.seller?.sellerCredit }}</text
              >
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 引入 uni-icons 用于显示图标
// import uniIcons from '@/components/uni-icons/uni-icons.vue'
const app = getApp();
export default {
  components: {
    // uniIcons
  },
  data() {
    return {
      activeTab: 1, // 默认选中"推荐"
      keyword: '',
      tabs: [
        { value: -1, name: "收藏" },
        { value: 0, name: "推荐" },
      ],
      quickEntries: [
        { name: "鱼赚鱼鲤", icon: "/static/images/entry-yzyz.png", tag: "" },
        { name: "闲鱼副业", icon: "/static/images/entry-fuye.png", tag: "" },
        {
          name: "手机数码",
          icon: "/static/images/entry-shouji.png",
          tag: "快冲",
          tagType: "red-tag",
        },
        { name: "极速回收", icon: "/static/images/entry-huishou.png", tag: "" },
        { name: "二手车", icon: "/static/images/entry-car.png", tag: "" },
        { name: "分类", icon: "/static/images/entry-category.png", tag: "" },
        // 你可以继续添加更多快捷入口
      ],
      outletItems: [
        { image: "/static/images/outlet-item1.jpg", price: "9" },
        { image: "/static/images/outlet-item2.jpg", price: "148" },
        { image: "/static/images/outlet-item3.jpg", desc: "1元起拍" },
        { image: "/static/images/outlet-item4.jpg", desc: "5.01可用" },
        { image: "/static/images/outlet-item1.jpg", price: "99" },
      ],
      products: [
        // 模拟商品数据
        {
          id: 1,
          image: "/static/images/product1.jpg",
          title: "包邮 (说明帖) サカナクション 符里的海洋诗",
          price: "52",
          wants: 55,
          sellerAvatar: "/static/images/avatar1.jpg",
          sellerName: "一只小...",
          sellerCredit: "卖家信用极好",
          isFreeShipping: true,
        },
        {
          id: 2,
          image: "/static/images/product2.jpg",
          title: "包邮 p5x玩家冒充p5老玩家服务 p5r云玩家 冒充高达seed玩家",
          price: "5",
          wants: 4,
          sellerAvatar: "/static/images/avatar2.jpg",
          sellerName: "Seker_7",
          sellerCredit: "卖家信用优秀",
          isFreeShipping: true,
        },
        {
          id: 3,
          image: "/static/images/product3.jpg",
          title: "三体漫画 典藏版 全套未拆封 送海报",
          price: "128",
          wants: 23,
          sellerAvatar: "/static/images/avatar1.jpg",
          sellerName: "科幻迷",
          sellerCredit: "卖家信用良好",
          isFreeShipping: false,
        },
        {
          id: 4,
          image: "/static/images/product4.jpg",
          title: "「活下去」中古日系短袖T恤 M码",
          price: "75",
          wants: 12,
          sellerAvatar: "/static/images/avatar2.jpg",
          sellerName: "复古潮人",
          sellerCredit: "卖家信用优秀",
          isFreeShipping: true,
        },
        {
          id: 5,
          image: "/static/images/product1.jpg",
          title: "二手Switch游戏卡带 马里奥奥德赛",
          price: "260",
          wants: 78,
          sellerAvatar: "/static/images/avatar1.jpg",
          sellerName: "游戏玩家",
          sellerCredit: "卖家信用极好",
          isFreeShipping: false,
        },
        {
          id: 6,
          image: "/static/images/product2.jpg",
          title: "包邮 9成新Kindle Paperwhite4 阅读器",
          price: "450",
          wants: 33,
          sellerAvatar: "/static/images/avatar2.jpg",
          sellerName: "读书爱好者",
          sellerCredit: "卖家信用优秀",
          isFreeShipping: true,
        },
      ],
      column1Products: [],
      column2Products: [],
    };
  },
  created() {
    // this.distributeProducts();
    this.loadCategories();
    this.getRecommend();
  },
  onShow() {
    this.getUserInfo();
  },
  methods: {
    changeTab(index) {
      this.activeTab = index;
      // 实际项目中，切换tab会重新请求对应分类的商品数据
      // 这里为了演示，可以简单重新分配或者清空商品列表
      // this.distributeProducts(); // 简单示例，实际可能要加载不同数据
      this.column1Products = [];
      this.column2Products = [];
      this.getRecommend()
    },
    clickProduct(item) {
      if(uni.getStorageSync('product').id !== item.id){
        uni.setStorageSync("product", item);
      }
      uni.navigateTo({
        url:
          "/pages/tb/product/productDetail?productId=" +
          item.id +
          "&type=1",
      });
    },
    handleSearch(){
      this.column1Products = []
      this.column2Products = []
      this.getRecommend()
    },
    getRecommend() {
      app.globalData.Request.post(
        app.globalData.ApiConstant.Product.recommend,
        {
          categoryId: this.tabs[this.activeTab].value,
          name: this.keyword
        }
      )
        .then((res) => {
          console.log(res);
          if (res.success) {
            let i = 0
            for (let item of res.data) {
              console.log(item);
              if(i % 2 == 0){
                this.column1Products.push(item);
              }else {
                this.column2Products.push(item);
              }
              i = i+1
            }
          } else {
            //有异常
          }
        })
        .catch((err) => {})
        .finally(() => {});
    },
    getFirstImageUrl(urls) {
      if (!urls) return "";
      try {
        // 尝试解析JSON数组
        const parsedUrls = JSON.parse(urls);
        if (Array.isArray(parsedUrls) && parsedUrls.length > 0) {
          return parsedUrls[0];
        }
      } catch (e) {
        // 解析失败，则按逗号分隔
        const urlArray = urls.split(",");
        if (urlArray.length > 0 && urlArray[0].trim() !== "") {
          return urlArray[0].trim();
        }
      }
      return ""; // 如果都无效，返回空
    },
    distributeProducts() {
      this.column1Products = [];
      this.column2Products = [];
      this.products.forEach((product, index) => {
        if (index % 2 === 0) {
          this.column1Products.push(product);
        } else {
          this.column2Products.push(product);
        }
      });
    },
    getCreditClass(creditText) {
      if(!creditText) return "";
      if (creditText.includes("极好")) return "credit-excellent";
      if (creditText.includes("优秀")) return "credit-good";
      if (creditText.includes("良好")) return "credit-fair";
      return "";
    },
    getUserInfo(){
      if(uni.getStorageSync('token')){
				app.globalData.Request.post(app.globalData.ApiConstant.User.userInfo,{}).then((res) => {
          console.log(res)
          if (res.success) {
            const userInfo = {
              favoriteProductIds: res.favoriteProductIds,
              likeProductIds: res.likeProductIds,
              buyCount: res.buyCount,
              myProductCount: res.myProductCount,
              sellerCount: res.sellerCount,
              sellerTotalAmount: res.sellerTotalAmount,
              defaultAddress: res.defaultAddress,
              ...res.user
            }
            uni.setStorageSync('userInfo',userInfo)
          } else {
            //有异常
          }
        }).catch((err) => {})
        .finally(() => {});
			}
      
    },
    // 加载分类列表
    loadCategories() {
      app.globalData.Request.post(app.globalData.ApiConstant.Category.list, {}, {showLoad : false}).then(res => {
        console.log('Category list API response:', res);
        if (res.success && res.data && Array.isArray(res.data)) {
          // 将后端返回的 { id, name } 格式转换为 { value, text }

          this.tabs = [...this.tabs, ...res.data.map(item => ({
              value: item.id, // 假设分类ID是 number 或 string
              name: item.name,
              // tag: 'qvq'
          }))];
          // 如果有默认选中逻辑，可以在这里设置 this.categoryId
          // 例如：this.categoryId = this.categoryList[0]?.value; // 默认选中第一个
        } else {
          uni.showToast({ title: res.message || '加载分类失败', icon: 'none' });
          this.categoryList = []; // 确保是空数组
        }
      }).catch(err => {
          console.error('Load categories API error:', err);
          uni.showToast({ title: '加载分类失败', icon: 'none' });
            this.categoryList = []; // 确保是空数组
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f4f4f4;
  padding-bottom: 50px; // 为底部tabbar留出空间，如果用原生tabbar则不需要
}

/* 1. 顶部搜索栏 */
.top-search-bar {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff; // 根据截图背景可能是渐变或纯色，这里用白色
  // position: sticky; // 如果需要吸顶
  // top: 0;
  // z-index: 999;

  .sign-in {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-right: 8px;
    .signin-icon {
      width: 28px;
      height: 28px;
    }
    text {
      font-size: 10px;
      color: #ff8c00; // 签到文字颜色
    }
  }

  .search-input-wrapper {
    flex-grow: 1;
    display: flex;
    align-items: center;
    background-color: #f0f0f0;
    border-radius: 18px;
    padding: 0 10px;
    height: 36px;
    .search-icon-inner {
      margin-right: 5px;
    }
    .search-input {
      flex-grow: 1;
      font-size: 14px;
      height: 100%;
      color: #333;
      &::placeholder {
        color: #999;
      }
    }
  }
  .camera-icon {
    margin: 0 10px;
  }
  .search-btn {
    background-color: #000;
    color: #fff;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

/* 2. 横向滚动Tab导航 */
.scroll-tabs {
  background-color: #fff;
  white-space: nowrap; // 关键属性，让内容不换行
  padding: 10px 0 5px 10px;
  border-bottom: 1px solid #eee;

  .tab-item {
    display: inline-block; // 关键属性
    padding: 5px 12px;
    font-size: 15px;
    color: #666;
    position: relative;
    margin-right: 5px;

    &.active {
      color: #333;
      font-weight: bold;
      &::after {
        content: "";
        position: absolute;
        bottom: -5px; // 根据实际效果调整
        left: 50%;
        transform: translateX(-50%);
        width: 20px;
        height: 3px;
        background-color: #ffd000; // 闲鱼黄
        border-radius: 2px;
      }
    }
    .tab-tag {
      // "省钱神券"的标签
      position: absolute;
      top: -5px;
      right: -5px;
      background-color: red; // 示例颜色
      color: white;
      font-size: 9px;
      padding: 1px 3px;
      border-radius: 3px;
      transform: scale(0.8);
    }
  }
}

/* 3. 快捷入口图标区域 */
.quick-entry {
  display: flex;
  flex-wrap: wrap;
  background-color: #fff;
  padding: 15px 5px 5px; // 上15，左右5，下5
  .entry-item {
    width: 20%; // 一行5个
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 10px;
    position: relative;

    .entry-icon {
      width: 40px;
      height: 40px;
      margin-bottom: 5px;
    }
    .entry-text {
      font-size: 12px;
      color: #333;
    }
    .entry-tag {
      position: absolute;
      top: -2px;
      right: 5px;
      font-size: 9px;
      padding: 1px 4px;
      border-radius: 3px;
      color: white;
      &.red-tag {
        background-color: red;
      }
      // 可以添加更多tag样式
    }
  }
}

/* 4. "Outlets捡漏" 横向滚动商品区域 */
.outlets-section {
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 10px;
  .outlets-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .outlets-title-icon {
      width: 60px; // 根据实际图片调整
      height: 20px;
      margin-right: 5px;
    }
    .outlets-title-text {
      // "闲鱼奥莱"
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
    .outlets-subtitle {
      // "电商退换货"
      font-size: 12px;
      color: #999;
      margin-left: 8px;
      background-color: #f0f0f0;
      padding: 2px 5px;
      border-radius: 3px;
    }
  }
  .outlets-scroll {
    white-space: nowrap;
    .outlet-item {
      display: inline-flex; // 使用inline-flex使内部元素能更好控制
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 90px; // 根据实际内容调整
      margin-right: 10px;
      text-align: center;
      .outlet-image {
        width: 70px;
        height: 70px;
        border-radius: 5px;
        background-color: #eee; // 占位背景
      }
      .outlet-price {
        font-size: 14px;
        color: #ff5000;
        font-weight: bold;
        margin-top: 5px;
      }
      .outlet-desc {
        font-size: 12px;
        color: #ff5000;
        border: 1px solid #ff5000;
        padding: 2px 5px;
        border-radius: 3px;
        margin-top: 5px;
      }
    }
  }
}

/* 5. 商品列表 */
.product-list-title {
  font-size: 16px;
  font-weight: bold;
  padding: 10px 10px 0;
  background-color: #f4f4f4; // 与页面背景色一致
}
.product-list {
  display: flex;
  justify-content: space-between;
  padding: 10px; // 整体列表的左右边距
  background-color: #f4f4f4; // 与页面背景色一致

  .column {
    width: 48.5%; // 为中间的间隙留出空间， (100 - 3) / 2
    display: flex;
    flex-direction: column;
  }

  .product-item {
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 10px; // 商品卡片之间的垂直间距
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    .product-image {
      width: 100%;
      // height: 180px; // mode="widthFix" 会自动计算高度，保持比例
      background-color: #eee; // 占位背景
    }

    .product-info {
      padding: 8px;

      .product-title {
        font-size: 14px;
        color: #333;
        line-height: 1.4;
        // 多行省略
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2; // 显示两行
        -webkit-box-orient: vertical;
        margin-bottom: 5px;
        min-height: 38px; // 保证两行的高度

        .shipping-tag {
          background-color: #ffedd9; // 包邮标签背景色
          color: #ff8c1a; // 包邮标签文字颜色
          font-size: 10px;
          padding: 1px 4px;
          border-radius: 3px;
          margin-right: 4px;
        }
      }

      .product-meta {
        display: flex;
        align-items: baseline;
        justify-content: space-between;
        margin-bottom: 8px;

        .product-price {
          font-size: 16px;
          color: #ff5000;
          font-weight: bold;
        }
        .product-wants {
          font-size: 11px;
          color: #999;
        }
      }

      .seller-info {
        display: flex;
        align-items: center;
        .seller-avatar {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          margin-right: 5px;
          background-color: #ccc;
        }
        .seller-name {
          font-size: 12px;
          color: #666;
          margin-right: 5px;
          // 名字过长省略
          max-width: 60px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .seller-credit {
          font-size: 10px;
          padding: 1px 5px;
          border-radius: 8px; // 圆角胶囊
          &.credit-excellent {
            // 极好
            background-color: #fff0e6; // 示例淡橙色
            color: #ff7f2a;
          }
          &.credit-good {
            // 优秀
            background-color: #e6f7ff; // 示例淡蓝色
            color: #1890ff;
          }
          &.credit-fair {
            // 良好
            background-color: #f6ffed; // 示例淡绿色
            color: #52c41a;
          }
        }
      }
    }
  }
}
</style>
